package com.example.administrator.basedemos.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.basedemos.R;
import com.example.administrator.basedemos.adapter.MainAdapter;
import com.example.administrator.basedemos.utils.LogUtil;
import com.example.net.utils.TmtUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import butterknife.BindView;


/**
 * 创建者     ZCL
 * 创建时间   2018/10/9 12:01
 * 描述	      ${TODO}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class InterViewQuestionActivity extends BaseZcActivity implements BaseQuickAdapter.OnItemClickListener {

    private static final String TAG = "InterViewQuestionActivity";
    @BindView(R.id.recyclerview_mm)
    RecyclerView mRecyclerviewMm;
    @BindView(R.id.recyclerview_mw)
    RecyclerView mRecyclerviewMw;
    private MainAdapter mAdapter;
    private int PERMISSION_REQUESTCODE = 11;
    private MyAsyncTask mMyAsyncTask;

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        switch (position) {
            case 0:
                permission();
                break;
            case 1:
                mMyAsyncTask = new MyAsyncTask();
                mMyAsyncTask.execute("哈哈");//哈哈对应第一个参数

                break;
        }
    }

    private void permission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //没有授权
            TmtUtils.midToast(InterViewQuestionActivity.this, "没有授权!");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_REQUESTCODE);
        } else {
            TmtUtils.midToast(InterViewQuestionActivity.this, "授权完毕!");
            //已经授权
            //call();
        }
    }

    public void call() {
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri uri = Uri.parse("tel:" + "10086");
            intent.setData(uri);
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    /**
     * * 处理权限请求结果
     *
     * @param requestCode* 请求权限时传入的请求码，用于区别是哪一次请求的
     * @param permissions  所请求的所有权限的数组
     * @param grantResults 权限授予结果，和 permissions 数组参数中的权限一一对应，元素值为两种情况，如下:
     *                     授予: PackageManager.PERMISSION_GRANTED
     *                     拒绝: PackageManager.PERMISSION_DENIED
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 10:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户点击了同意授权
                    //call();
                } else {
                    //用户拒绝了授权
                    Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    public static void showMessageOKCancel(final Activity context, String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setPositiveButton(context.getString(R.string.确认), okListener)
                .setNegativeButton(context.getString(R.string.取消), null)
                .create()
                .show();

    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_interview_quesetion;
    }

    @Override
    protected void initData() {
        mSetting.setVisibility(View.GONE);
        mConfirm.setVisibility(View.GONE);
        mToolbar.setBackgroundColor(Color.YELLOW);
        //setLayoutMangerHorizontal(mRecyclerviewMm);
        mRecyclerviewMm.setLayoutManager(new GridLayoutManager(this,4, LinearLayoutManager.VERTICAL,false));
        ArrayList<String> list = new ArrayList<>();
        list.add("手机Phone权限");
        list.add("执行AsyncTask");
        mAdapter = new MainAdapter(R.layout.main_item, list);
        mRecyclerviewMm.setAdapter(mAdapter);
    }

    @Override
    public void initListener() {
        super.initListener();
        if (mAdapter != null)
            mAdapter.setOnItemClickListener(this);
    }

    public class CycleView extends View {//回值圆环实现郭城
        Paint mPaint = new Paint();

        public CycleView(Context context) {
            this(context, null);
        }

        public CycleView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initView();
        }

        private void initView() {
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(20);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawCircle(100, 100, 50, mPaint);
        }
    }

    private class MyHandler extends Handler {

        private final WeakReference<InterViewQuestionActivity> mActivity;

        private MyHandler(Activity activity) {//使用弱引用可以解决报错问题
            mActivity = new WeakReference<>((InterViewQuestionActivity) activity);
            //new  Handler().removeCallbacksAndMessages(null);//或者destory移除所有
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }

    private class MyAsyncTask extends AsyncTask<String ,Integer,String>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            LogUtil.util(TAG,"onPreExecute");//1
        }
        @Override
        protected String doInBackground(String... strings) {//2
            LogUtil.util(TAG,"doInBackground---"+strings[0]);
            for (int i = 0; i < 5; i++) {
                if (isCancelled())
                    break;//如果是已经结束任务就停止耗时操作,不做判断发出取消操作后是无法结束耗时操作的
                publishProgress(i);
            }
            return "Game Over";
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            LogUtil.util(TAG,"onCancelled");
        }
        @Override
        protected void onProgressUpdate(Integer... values) {//3
            super.onProgressUpdate(values);
            if (isCancelled())
               return;
            LogUtil.util(TAG,"onProgressUpdate---"+values[0]);
        }
        @Override
        protected void onPostExecute(String o) {//4
            super.onPostExecute(o);
            LogUtil.util(TAG,"onPostExecute---"+o);
            mMyAsyncTask.cancel(true);
        }
        @Override
        protected void onCancelled(String o) {
            super.onCancelled(o);
            LogUtil.util(TAG,"onCancelled---"+o);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMyAsyncTask!=null&&mMyAsyncTask.getStatus()==AsyncTask.Status.RUNNING)
            mMyAsyncTask.cancel(true);//如果是界面被遮挡后就停止执行任务防止阻塞其他进程
    }
}
